package com.heima.hellospring.service;

import com.heima.hellospring.constant.REnum;
import com.heima.hellospring.domain.Student;
import com.heima.hellospring.exception.RException;
import com.heima.hellospring.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * created by tms
 * 2024-11-17
 * 学生服务类
*/
@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    public Page<Student> getAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    public Page<Student> getAll(Example<Student> example, Pageable pageable) {
        return studentRepository.findAll(example,pageable);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Student findById(Integer id) {
        return studentRepository.findById(id).orElse(null);
    }

    /**
     * 根据name查询
     * @param name
     * @return
     */
   public List<Student> findByName(String name) {
       return studentRepository.findByNameLike(name);
   }

    /**
     *
     * 插入数据
     * @param student
     */
   public Student insert(Student student) {
       return studentRepository.save(student);
   }

    /**
     *
     * 修改数据
     * @param student
     */
    public Student update(Student student) {
        return studentRepository.save(student);
    }

    /**
     *
     * 删除数据
     * @param id
     */
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public Student validateStudentUsername(String studentid,String password) {
        List<Student> students = studentRepository.findByStudentid(studentid);
        if (!students.isEmpty()) {
            Student student = students.get(0);
            if(student.getPassword().equals(password)) {
                return student;
            }
            else{
                throw new RException(REnum.LOGIN_ERR);
            }
        }
        else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    public void deleteByIds(List<Integer> ids) {
        studentRepository.deleteAllById(ids);
    }
}